package com.gel.shortLink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gel.shortLink.admin.common.enums.UserErrorCodeEnum;
import com.gel.shortLink.admin.convention.exception.ClientException;
import com.gel.shortLink.admin.dao.entity.User;
import com.gel.shortLink.admin.dto.req.UserLoginRepDTO;
import com.gel.shortLink.admin.dto.req.UserReqDTO;
import com.gel.shortLink.admin.dto.req.UserUpdateRepDTO;
import com.gel.shortLink.admin.dto.resp.UserLoginRespDTO;
import com.gel.shortLink.admin.dto.resp.UserRespDTO;
import com.gel.shortLink.admin.service.GroupService;
import com.gel.shortLink.admin.service.UserService;
import com.gel.shortLink.admin.dao.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.gel.shortLink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;

/**
* @author gel
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-07-07 11:10:42
*/
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, username);
        User user = baseMapper.selectOne(queryWrapper);
        if(user == null){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(user, userRespDTO);
        return userRespDTO;
    }

    @Override
    public boolean hasUserName(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserReqDTO requestParam) {
        if (!hasUserName(requestParam.getUsername())) {
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }
        /*通过分布式锁防止同一用户名进行恶意注册*/
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        try {
            if (lock.tryLock()) {
                int insert = baseMapper.insert(BeanUtil.toBean(requestParam, User.class));
                if (insert < 1) {
                    throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
                }
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                groupService.saveGroup(requestParam.getUsername(), "默认分组");

                return;
            }
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }finally{
            lock.unlock();
        }
    }

    @Override
    public UserLoginRespDTO login(UserLoginRepDTO requestParam) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, requestParam.getUsername())
                .eq(User::getPassword, requestParam.getPassword())
                .eq(User::getDelFlag, 0);
        User user = baseMapper.selectOne(queryWrapper);
        if(user == null) {
            throw  new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        Boolean hasKey = stringRedisTemplate.hasKey("login_" + user.getUsername());
        if(hasKey!=null&&hasKey){
            throw new ClientException(UserErrorCodeEnum.USER_LOGIN_ERROR);
        }

        String uuid= UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_"+user.getUsername(), uuid, JSONUtil.toJsonStr( user));
        stringRedisTemplate.expire("login_"+user.getUsername(),30L, TimeUnit.DAYS);
        UserLoginRespDTO userLoginRespDTO = UserLoginRespDTO.builder()
                .username(user.getUsername())
                .realName(user.getRealName())
                .token(uuid)
                .build();
        return userLoginRespDTO;
    }

    @Override
    public Boolean checkLogin(String username, String token) {
       return stringRedisTemplate.opsForHash().get("login_"+username,token)!=null;
    }

    @Override
    public void logout(String username, String token) {
        if(checkLogin(username,token)){
            stringRedisTemplate.delete("login_"+username);
            return;
        }
        throw new ClientException("用户token不存在或用户未登录");

    }

    @Override
    public void update(UserUpdateRepDTO requestParam) {
        Boolean checkLogin = checkLogin(requestParam.getUsername(), requestParam.getToken());
        if(!checkLogin){
            throw new ClientException("当前用户未登录");
        }
        LambdaUpdateWrapper<User> updateWrapper = Wrappers.lambdaUpdate(User.class)
                .eq(User::getUsername, requestParam.getUsername())
                .eq(User::getDelFlag, 0);
        int update = baseMapper.update(BeanUtil.toBean(requestParam, User.class), updateWrapper);
        if(update<1){
            throw new ClientException("用户修改异常");
        }
    }
}




